package com.parktech.sun.web.controller.management.aboutus;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.aboutus.Cooperation;
import com.parktech.sun.domain.model.specialtopic.SpecialTopicCategory;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.aboutus.CooperationService;
import com.parktech.sun.utils.FileHelper;
import com.parktech.sun.utils.ImageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * User: Think
 * Date: 11-1-15
 * Time: 下午1:18
 */
@Controller
@RequestMapping("/management/aboutus/cooperation")
public class CooperationController {
    
    private int pageSize = Constants.PAGINATION_PAGE_SIZE;

    private CooperationService cooperationService;

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Autowired
    public CooperationController(CooperationService cooperationService) {
        this.cooperationService = cooperationService;
    }

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView search(@ModelAttribute CooperationSearchForm cooperationSearchForm) {

        Page page = new Page(pageSize, cooperationSearchForm.getPageNo());

        ModelAndView modelAndView = new ModelAndView("management/aboutus/cooperationSearch");

        return modelAndView.addObject(
                cooperationService.search(
                        cooperationSearchForm.getTitle(), cooperationSearchForm.getPublishStatus(), page));
    }

    @RequestMapping(value = "/search", method = RequestMethod.DELETE)
    public String delete(@RequestParam("cooperationIds") Long[] cooperationIds) {
        cooperationService.deleteAll(cooperationIds);
        return "redirect:search";
    }

    @ModelAttribute("cooperation")
    public Cooperation populateModel(HttpServletRequest request) {
        String strId = request.getParameter("id");

        if (strId == null || strId.equals("-1")) {
            return new Cooperation();
        }
        return cooperationService.getById(new Long(strId));
    }

    @ModelAttribute("allPublishStatus")
    public Map<Integer, String> populateAllPublishStatus() {
        Map<Integer, String> allPublishStatus = new HashMap<Integer, String>();
//        allPublishStatus.put(-1, "所有");
        allPublishStatus.put(0, "未发布");
        allPublishStatus.put(1, "已发布");
        return allPublishStatus;
    }

    @RequestMapping(value = "/{cooperationId}", method = RequestMethod.GET)
    public String edit(@PathVariable Long cooperationId, Model model) {
        Cooperation cooperation = cooperationService.getById(cooperationId);
        model.addAttribute(cooperation);
        return "management/aboutus/cooperationForm";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute(new Cooperation());
        return "management/aboutus/cooperationForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid Cooperation cooperation, BindingResult result,
                       @RequestParam("logoImage") MultipartFile logoImage,
                       HttpServletRequest request) throws IOException {

        if (result.hasErrors()) {
            return "management/aboutus/cooperationForm";
        }
        cooperationService.clearThenSaveOrUpdateBean(cooperation);

        if (logoImage != null && !logoImage.isEmpty()) {
            processImage(cooperation, logoImage, request.getSession().getServletContext());
        }

        cooperationService.saveOrUpdateBean(cooperation);

        return "redirect:/management/aboutus/cooperation/search";
    }

    private void processImage(Cooperation cooperation, MultipartFile image, ServletContext servletContext) throws IOException {

        String specialTopicPath = servletContext.getRealPath("/upload/aboutus/" + cooperation.getId());
        File specialTopicDir = new File(specialTopicPath);
        if (!specialTopicDir.exists()) specialTopicDir.mkdirs();

        File imageFile = new File(specialTopicDir, image.getOriginalFilename());
        if (imageFile.exists()) {
            imageFile.delete();
        }
        ImageHelper.resizeFix(image.getInputStream(), imageFile, 150, 75);
        cooperation.setLogoName(image.getOriginalFilename());
    }

}
